package com.kaishengit.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class CheckUserFilter extends AbstractFilter{

	//²»µÇÂ½¶¼ÄÜ·ÃÎÊµÄÒ³Ãædd
	private List<String> safeURL = new ArrayList<String>();
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		safeURL.add("/");
		safeURL.add("/index.jsp");
		safeURL.add("/hello.jspx");
	}
	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		
		HttpServletRequest request = (HttpServletRequest)req;
		HttpServletResponse response= (HttpServletResponse)resp;
		
		//»ñÈ¡ÇëÇóµÄURL
		String url = request.getRequestURI();
		url = url.substring(url.lastIndexOf("/"));
		
		//ÅÐ¶ÏÇëÇóµÄURLÊÇ²»ÊÇÔÚ°²È«ÁÐ±íÖÐ
		if(safeURL.contains(url)){
			//Èç¹ûÔÚ£¬Ôò·ÅÐÐ
			chain.doFilter(request, response);
		}else{
			//Èç¹û²»ÔÚÔòÑéÖ¤
			HttpSession session = request.getSession(false);
			//Èç¹ûÓÃ»§µÚÒ»´ÎÇëÇó£¬ÔòsessionÎªnull,Èç¹ûÎªnull,ÔòÐèÒªµÇÂ¼
			if(session == null){
				response.sendRedirect("index.jsp");
				//response.sendError(403);
			}else{
				//´ÓsessionÖÐ»ñÈ¡µÇÂ¼ºóµÄ´æÈëµÄ¶ÔÏó
				String name = (String) session.getAttribute("currUser");
				//Èç¹û¸Ã¶ÔÏó²»´æÔÚ£¬ÔòÖØÐÂµÇÂ¼
				if(name == null){
					response.sendRedirect("index.jsp");
					//response.sendError(403,"(*^__^*) ÎûÎû¡­¡­");
				}else{
					//·ñÔò£¬·ÅÐÐ
					chain.doFilter(request, response);
				}
			}
		}
	}

}
